package com.pactera.jep.service.sys.security.spring.conf;

import com.pactera.jep.service.sys.util.AESEncoder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import com.pactera.jep.service.sys.util.MD5Encoder;
import com.pactera.jep.service.sys.util.UserNameCache;

/**
 * 用MD5算法对密码进行加密以及比较密码
 *
 * @author ghost
 */
@Component
public class MD5PasswordEncoder implements PasswordEncoder {

    private final static Logger logger = LoggerFactory.getLogger(MD5PasswordEncoder.class);

    @Autowired
    private UserNameCache userNameCache;

    @Override
    public String encode(CharSequence rawPassword) {
        if (StringUtils.isEmpty(rawPassword)) {
            logger.error("待加密的密码为空！");
        } else {
            if (StringUtils.isEmpty(userNameCache.getName())) {
                logger.debug("传入的用户名为空！");
            } else {
                return MD5Encoder.encode((String) rawPassword, userNameCache.getName(), 1);
            }
        }
        return null;
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        String decodePassword = AESEncoder.decrypt(rawPassword.toString());
        if (decodePassword.contains(".")) {
            decodePassword = decodePassword.split("\\.")[0];
        }
        if (StringUtils.isEmpty(decodePassword) || StringUtils.isEmpty(encodedPassword)) {
            logger.error("传入的rawPassword或encodedPassword为空！");
            return false;
        } else {
            return encode(decodePassword).equals(encodedPassword);
        }
    }

}
